/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework.adapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;

import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;

/**
 * Default implementation of the {@link AdvisorAdapterRegistry} interface.
 * Supports {@link org.aopalliance.intercept.MethodInterceptor},
 * {@link org.springframework.aop.MethodBeforeAdvice},
 * {@link org.springframework.aop.AfterReturningAdvice},
 * {@link org.springframework.aop.ThrowsAdvice}.
 *<br> AdvisorAdapterRegistry接口的默认实现。 支持 MethodInterceptor、MethodBeforeAdvice、AfterReturningAdvice 和 ThrowsAdvice。
 * @author Rod Johnson
 * @author Rob Harrop
 * @author Juergen Hoeller
 */
@SuppressWarnings("serial")
public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {

	private final List<AdvisorAdapter> adapters = new ArrayList<>(3);


	/**
	 * Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters.
	 */
	public DefaultAdvisorAdapterRegistry() {
		registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
		registerAdvisorAdapter(new AfterReturningAdviceAdapter());
		registerAdvisorAdapter(new ThrowsAdviceAdapter());
	}


	@Override
	public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
		//1、如果 adviceObject 就是 Advisor 直接返回
		if (adviceObject instanceof Advisor advisor) {
			return advisor;
		}
		if (!(adviceObject instanceof Advice advice)) {
			throw new UnknownAdviceTypeException(adviceObject);
		}
		//2、advice是 MethodInterceptor ，创建 DefaultPointcutAdvisor并返回
		if (advice instanceof MethodInterceptor) {
			// So well-known it doesn't even need an adapter.
			return new DefaultPointcutAdvisor(advice);
		}
		//3、遍历适配器，找到适配的适配器并返回对应的 DefaultPointcutAdvisor
		for (AdvisorAdapter adapter : this.adapters) {
			// Check that it is supported.
			if (adapter.supportsAdvice(advice)) {
				return new DefaultPointcutAdvisor(advice);
			}
		}
		throw new UnknownAdviceTypeException(advice);
	}

	/**
	 * 该函数的作用是从给定的Advisor对象中获取MethodInterceptor数组，
	 * 这些拦截器将在AOP（面向切面编程）中用于拦截方法调用。
	 * 1) 首先，函数创建一个MethodInterceptor列表，
	 * 2)并检查Advisor中的Advice是否是MethodInterceptor类型，如果是则直接添加到列表中。
	 * 3)接着，函数遍历所有AdvisorAdapter，检查它们是否支持当前的Advice，
	 * 4)如果支持则通过adapter.getInterceptor(advisor)获取拦截器并添加到列表中。
	 * 5)如果最终列表为空，则抛出UnknownAdviceTypeException异常，
	 * 6)否则将列表转换为数组并返回。
	 * 该函数在Spring AOP框架中扮演着关键角色，确保每个Advisor都能正确地转换为拦截器链，
	 * 从而在方法调用时执行相应的切面逻辑
	 * 。调用该函数的DefaultAdvisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice方法用于构建完整的拦截器链，
	 * 确保AOP代理能够正确地处理方法调用。该函数在Spring AOP框架中至关重要，确保了切面逻辑的正确执行，从而增强了Spring框架的灵活性和可扩展性。
	 * @param advisor the Advisor to find an interceptor for
	 * @return
	 * @throws UnknownAdviceTypeException
	 */
	@Override
	public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
		List<MethodInterceptor> interceptors = new ArrayList<>(3);
		//1、获取advisor中的advice，如果是MethodInterceptor 直接添加到列表中
		Advice advice = advisor.getAdvice();
		if (advice instanceof MethodInterceptor methodInterceptor) {
			interceptors.add(methodInterceptor);
		}
		//2、遍历适配器，找到适配的适配器并返回对应的拦截器
		for (AdvisorAdapter adapter : this.adapters) {
			if (adapter.supportsAdvice(advice)) {
				interceptors.add(adapter.getInterceptor(advisor));
			}
		}
		if (interceptors.isEmpty()) {
			throw new UnknownAdviceTypeException(advisor.getAdvice());
		}
		return interceptors.toArray(new MethodInterceptor[0]);
	}

	@Override
	public void registerAdvisorAdapter(AdvisorAdapter adapter) {
		this.adapters.add(adapter);
	}

}
